//
//  DCViewController.m
//  tarbarTest
//
//  Created by Joinwe on 15/12/8.
//  Copyright © 2015年 Joinwe. All rights reserved.
//

#import "DCViewController.h"
#import <Masonry/Masonry.h>
#import <MMPlaceHolder/MMPlaceHolder.h>
#import "UIView+Masonry_LJC.h"
#import "TestCell.h"

#define WS(weakSelf)  __weak __typeof(&*self)weakSelf = self;

@interface DCViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UIButton *growingButton;
@property (nonatomic, assign) CGFloat scacle;


@property (nonatomic, strong) UIButton *remarkButton;
@property (nonatomic, assign) BOOL isExpanded;
@property (nonatomic, strong) MASConstraint *height;


@property (nonatomic, strong) UIView *greenView;
@property (nonatomic, strong) UIView *blueView;
@property (nonatomic, assign) BOOL isExpaned;

@property (nonatomic, strong) NSMutableArray *viewArray;
@property (nonatomic, assign) BOOL isNormal;


@property (nonatomic, strong) UIView *redView;
@property (nonatomic, assign) CGFloat padding;


@property (nonatomic, strong) UIScrollView *scrollView;


@property (nonatomic, strong) NSMutableArray *expandStates;


@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@end

@implementation DCViewController

- (instancetype)initWithTitle:(NSString *)title {
    if (self = [super init]) {
        self.title = title;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor lightGrayColor];
    
    if (kIOSVersion >= 7.0) {
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    
    [self configTableView];
}

/**测试复杂视图**/
- (void)configScrollView {
    self.scrollView = [[UIScrollView alloc] init];
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    UIView *headerView = [[UIView alloc] init];
    [self.scrollView addSubview:headerView];
    
    UIImageView *imgView = [[UIImageView alloc] init];
    [headerView addSubview:imgView];
    imgView.backgroundColor = [UIColor greenColor];
    imgView.layer.cornerRadius = 50;
    imgView.layer.masksToBounds = YES;
    imgView.layer.borderWidth = 0.5;
    imgView.layer.borderColor = [UIColor redColor].CGColor;
    
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    
    UILabel *tipLabel = [[UILabel alloc] init];
    tipLabel.text = @"这里是提示信息，通常会比较长，可能会超过两行。为了适配6.0，我们需要指定preferredMaxLayoutWidth，但是要注意，此属性一旦设置，不是只在6.0上生效，任意版本的系统的都有作用，因此此值设置得一定要准备，否则计算结果会不正确。我们一定要注意，不能给tableview的tableHeaderView和tableFooterView添加约束，在6.0及其以下版本上会crash，其它版本没有";
    tipLabel.textAlignment = NSTextAlignmentCenter;
    tipLabel.textColor = [UIColor blackColor];
    tipLabel.backgroundColor = [UIColor clearColor];
    tipLabel.numberOfLines = 0;
    tipLabel.preferredMaxLayoutWidth = screenWidth - 30;
    [headerView addSubview:tipLabel];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"Show detail" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor blueColor]];
    button.layer.cornerRadius = 6;
    button.clipsToBounds = YES;
    button.layer.masksToBounds = YES;
    
    [headerView addSubview:button];
    
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(0);
        make.width.mas_equalTo(self.view);
        make.bottom.mas_equalTo(button.mas_bottom).offset(60).priorityLow();
        make.height.greaterThanOrEqualTo(self.view);
    }];
    
    [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(80);
        make.centerX.mas_equalTo(headerView);
        make.width.height.mas_equalTo(100);
    }];
    
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.top.mas_equalTo(imgView.mas_bottom).offset(40);
    }];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_greaterThanOrEqualTo(tipLabel.mas_bottom).offset(80);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(45);
    }];
    
    [self.scrollView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(button.mas_bottom).offset(80).priorityLow();
        make.bottom.mas_greaterThanOrEqualTo(self.view);
    }];
}

- (void)configTableView {
    if (self.tableView != nil) {
        return;
    }
    self.tableView = [[UITableView alloc] init];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    NSArray *array = [self headerViewWithHeight:self.view.frame.size.height addToView:self.view];
    UIView *headerView = [array firstObject];
    [headerView layoutIfNeeded];
    UIButton *button = [array lastObject];
    CGFloat h = button.frame.size.height + button.frame.origin.y + 40;
    h = h < self.view.frame.size.height ? self.view.frame.size.height : h;
    
    [headerView removeFromSuperview];
    [self headerViewWithHeight:h addToView:nil];
}

- (NSArray *)headerViewWithHeight:(CGFloat)height addToView:(UIView *)toView {
    // 注意，绝对不能给tableheaderview直接添加约束，必闪退
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, height)];
    
    if (toView) {
        [toView addSubview:headerView];
    } else {
        self.tableView.tableHeaderView = headerView;
    }
    
    UIImageView *imgView = [[UIImageView alloc] init];
    [headerView addSubview:imgView];
    imgView.backgroundColor = [UIColor greenColor];
    imgView.layer.cornerRadius = 50;
    imgView.layer.masksToBounds = YES;
    imgView.layer.borderWidth = 0.5;
    imgView.layer.borderColor = [UIColor redColor].CGColor;
    
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    
    UILabel *tipLabel = [[UILabel alloc] init];
    tipLabel.text = @"这里是提示信息，通常会比较长，可能会超过两行。为了适配6.0，我们需要指定preferredMaxLayoutWidth，但是要注意，此属性一旦设置，不是只在6.0上生效，任意版本的系统的都有作用，因此此值设置得一定要准备，否则计算结果会不正确。我们一定要注意，不能给tableview的tableHeaderView和tableFooterView添加约束，在6.0及其以下版本上会crash，其它版本没有";
    tipLabel.textAlignment = NSTextAlignmentCenter;
    tipLabel.textColor = [UIColor blackColor];
    tipLabel.backgroundColor = [UIColor clearColor];
    tipLabel.numberOfLines = 0;
    tipLabel.preferredMaxLayoutWidth = screenWidth - 30;
    [headerView addSubview:tipLabel];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"Show detail" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor blueColor]];
    button.layer.cornerRadius = 6;
    button.clipsToBounds = YES;
    button.layer.masksToBounds = YES;
    
    [headerView addSubview:button];
    
    [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(80);
        make.centerX.mas_equalTo(headerView);
        make.width.height.mas_equalTo(100);
    }];
    
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).offset(15);
        make.right.mas_equalTo(self.view).offset(-15);
        make.top.mas_equalTo(imgView.mas_bottom).offset(40);
    }];
    
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_greaterThanOrEqualTo(tipLabel.mas_bottom).offset(80);
        make.left.mas_equalTo(tipLabel);
        make.right.mas_equalTo(tipLabel);
        make.height.mas_equalTo(45);
    }];
    
    return @[headerView, button];
}

/**tableViewCell布局**/
- (NSMutableArray *)dataSource {
    if (_dataSource == nil) {
        _dataSource = [[NSMutableArray alloc] init];
    }
    
    return _dataSource;
}

- (void)tableViewTest{
    self.tableView = [[UITableView alloc] init];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    for (NSUInteger i = 0; i < 10; ++i) {
        TestModel *model = [[TestModel alloc] init];
        model.title = @"这是一个测试标题";
        model.desc = @"安徽发顺丰垃圾分类；收费的；‘按时开放的；萨克发斯蒂芬斯蒂芬卡萨开发；啥的开发；奥卡福；萨克福克斯；联发科萨反馈萨芬卡萨；的反馈撒地方了卡萨东方红凯撒股份是开发干啥就放暑假大法官咖啡和看撒谎发两份哈哈发了客户开发和福利和士大夫 奥拉夫哈利法哈酸辣粉哈利法很拉风和萨拉发生了发货就爱上了发哈森林防火";
        
        [self.dataSource addObject:model];
    }
    
    [self.tableView reloadData];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"CellIdentifier";
    
    TestCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (!cell) {
        cell = [[TestCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    cell.indexPath = indexPath;
    cell.block = ^(NSIndexPath *path) {
        [tableView reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationFade];
    };
    TestModel *model = [self.dataSource objectAtIndex:indexPath.row];
    [cell configCellWithModel:model];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    TestModel *model = [self.dataSource objectAtIndex:indexPath.row];
    
    return [TestCell heightWithModel:model];
}

/**复杂scrollView**/
- (void)scrollViewTest{
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.pagingEnabled = NO;
    [self.view addSubview:self.scrollView];
    self.scrollView.backgroundColor = [UIColor lightGrayColor];
    
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    UILabel *lastLabel = nil;
    for (NSUInteger i = 0; i < 10; ++i) {
        UILabel *label = [[UILabel alloc] init];
        label.numberOfLines = 0;
        label.layer.borderColor = [UIColor greenColor].CGColor;
        label.layer.borderWidth = 2.0;
        label.text = [self randomText];
        label.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap:)];
        [label addGestureRecognizer:tap];
        
        // We must preferredMaxLayoutWidth property for adapting to iOS6.0
        label.preferredMaxLayoutWidth = screenWidth - 30;
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [self randomColor];
        [self.scrollView addSubview:label];
        
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15);
            make.right.mas_equalTo(self.view).offset(-15);
            
            if (lastLabel) {
                make.top.mas_equalTo(lastLabel.mas_bottom).offset(20);
            } else {
                make.top.mas_equalTo(self.scrollView).offset(20);
            }
            
            make.height.mas_equalTo(40);
        }];
        
        lastLabel = label;
        
        [self.expandStates addObject:[@[label, @(NO)] mutableCopy]];
    }
    
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
        
        // 让scrollview的contentSize随着内容的增多而变化
        make.bottom.mas_equalTo(lastLabel.mas_bottom).offset(20);
    }];
}

- (NSMutableArray *)expandStates {
    if (_expandStates == nil) {
        _expandStates = [[NSMutableArray alloc] init];
    }
    
    return _expandStates;
}

//- (UIColor *)randomColor {
//    CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
//    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from white
//    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black
//    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
//}
//
//- (NSString *)randomText {
//    CGFloat length = arc4random() % 150 + 5;
//    
//    NSMutableString *str = [[NSMutableString alloc] init];
//    for (NSUInteger i = 0; i < length; ++i) {
//        [str appendString:@"测试数据很长，"];
//    }
//    
//    return str;
//}

- (void)onTap:(UITapGestureRecognizer *)sender {
    UIView *tapView = sender.view;
    
    NSUInteger index = 0;
    for (NSMutableArray *array in self.expandStates) {
        UILabel *view = [array firstObject];
        
        if (view == tapView) {
            NSNumber *state = [array lastObject];
            
            // 当前是展开状态的话，就收缩
            if ([state boolValue] == YES) {
                [view mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(40);
                }];
            } else {
                UIView *preView = nil;
                UIView *nextView = nil;
                
                if (index - 1 < self.expandStates.count && index >= 1) {
                    preView = [[self.expandStates objectAtIndex:index - 1] firstObject];
                }
                
                if (index + 1 < self.expandStates.count) {
                    nextView = [[self.expandStates objectAtIndex:index + 1] firstObject];
                }
                
                [view mas_remakeConstraints:^(MASConstraintMaker *make) {
                    if (preView) {
                        make.top.mas_equalTo(preView.mas_bottom).offset(20);
                    } else {
                        make.top.mas_equalTo(20);
                    }
                    
                    make.left.mas_equalTo(15);
                    make.right.mas_equalTo(self.view).offset(-15);
                }];
                
                if (nextView) {
                    [nextView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.top.mas_equalTo(view.mas_bottom).offset(20);
                    }];
                }
            }
            
            [array replaceObjectAtIndex:1 withObject:@(!state.boolValue)];
            
            [self.view setNeedsUpdateConstraints];
            [self.view updateConstraintsIfNeeded];
            
            [UIView animateWithDuration:0.35 animations:^{
                [self.view layoutIfNeeded];
            } completion:^(BOOL finished) {
                
            }];
            break;
        }
        
        index++;
    }
}
/**ScrollerView布局**/
- (void)scrollViewLayout{
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.pagingEnabled = NO;
    [self.view addSubview:self.scrollView];
    self.scrollView.backgroundColor = [UIColor lightGrayColor];
    
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    UILabel *lastLabel = nil;
    for (NSUInteger i = 0; i < 20; ++i) {
        UILabel *label = [[UILabel alloc] init];
        label.numberOfLines = 0;
        label.layer.borderColor = [UIColor greenColor].CGColor;
        label.layer.borderWidth = 2.0;
        label.text = [self randomText];
        
        // We must preferredMaxLayoutWidth property for adapting to iOS6.0
        label.preferredMaxLayoutWidth = screenWidth - 30;
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [self randomColor];
        [self.scrollView addSubview:label];
        
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15);
            make.right.mas_equalTo(self.view).offset(-15);
            
            if (lastLabel) {
                make.top.mas_equalTo(lastLabel.mas_bottom).offset(20);
            } else {
                make.top.mas_equalTo(self.scrollView).offset(20);
            }
        }];
        
        lastLabel = label;
    }
    
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
        
        // 让scrollview的contentSize随着内容的增多而变化
        make.bottom.mas_equalTo(lastLabel.mas_bottom).offset(20);
    }];
}

- (UIColor *)randomColor {
    CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black
    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}

- (NSString *)randomText {
    CGFloat length = arc4random() % 50 + 5;
    
    NSMutableString *str = [[NSMutableString alloc] init];
    for (NSUInteger i = 0; i < length; ++i) {
        [str appendString:@"测试数据很长，"];
    }
    
    return str;
}

/**基本动画**/
- (void)basicAnimated{
    UIView *greenView = UIView.new;
    greenView.backgroundColor = UIColor.greenColor;
    greenView.layer.borderColor = UIColor.blackColor.CGColor;
    greenView.layer.borderWidth = 2;
    [self.view addSubview:greenView];
    
    UIView *redView = UIView.new;
    redView.backgroundColor = UIColor.redColor;
    redView.layer.borderColor = UIColor.blackColor.CGColor;
    redView.layer.borderWidth = 2;
    [self.view addSubview:redView];
    
    UIView *blueView = UIView.new;
    blueView.backgroundColor = UIColor.blueColor;
    blueView.layer.borderColor = UIColor.blackColor.CGColor;
    blueView.layer.borderWidth = 2;
    [self.view addSubview:blueView];
    self.greenView = greenView;
    self.redView = redView;
    self.blueView = blueView;
    
    // 使这三个控件等高
    self.padding = 10;
    CGFloat padding = self.padding;
    [greenView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(padding),
        make.left.mas_equalTo(padding),
        make.right.mas_equalTo(redView.mas_left).offset(-padding),
        make.bottom.mas_equalTo(blueView.mas_top).offset(-padding).priorityLow(),
        // 三个控件等高
        make.height.mas_equalTo(@[redView, blueView]);
        // 红、绿这两个控件等高
        make.width.mas_equalTo(redView);
        make.height.lessThanOrEqualTo(self.view);
    }];
    
    [redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.height.width.bottom.mas_equalTo(greenView);
        make.right.mas_equalTo(-padding);
        make.left.mas_equalTo(greenView.mas_right).offset(padding);
        make.height.mas_equalTo(@[greenView, blueView]);
    }];
    
    [blueView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@[greenView, redView]);
        make.bottom.mas_equalTo(-padding);
        make.left.mas_equalTo(padding);
        make.right.mas_equalTo(-padding);
    }];
    
    [self updateAnimated:NO];
}

- (void)updateAnimated:(BOOL)animated {
    CGFloat padding = self.padding >= 350 ? 10 : 350;
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    [self.blueView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-padding);
        make.top.mas_equalTo((screenHeight - 64) / 2 - 5);
        //    make.right.mas_equalTo(self.view.mas_right).offset(-padding);
    }];
    
    if (animated) {
        [self.view setNeedsUpdateConstraints];
        [self.view updateConstraintsIfNeeded];
        
        [UIView animateWithDuration:0.5 animations:^{
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {
            self.padding = padding;
            [self updateAnimated:YES];
        }];
    } else {
        [self.view layoutIfNeeded];
        
        [self updateAnimated:YES];
    }
}

/**multipliedBy的用法**/
- (void)multipliedBy{
    // Create views
    UIView *topView = [[UIView alloc] init];
    topView.backgroundColor = [UIColor redColor];
    [self.view addSubview:topView];
    
    UIView *topInnerView = [[UIView alloc] init];
    topInnerView.backgroundColor = [UIColor greenColor];
    [topView addSubview:topInnerView];
    
    UIView *bottomView = [[UIView alloc] init];
    bottomView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:bottomView];
    
    UIView *bottomInnerView = [[UIView alloc] init];
    bottomInnerView.backgroundColor = [UIColor blueColor];
    [bottomView addSubview:bottomInnerView];
    
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.height.mas_equalTo(bottomView);
    }];
    
    // width = height / 3
    [topInnerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(topView);
        //这是最关键的代码，使用multipliedBy必须是对同一个控件本身，比如，上面的代码中，我们都是对bottomInnerView.mas_width本身的，如果修改成相对于其它控件，会出问题。
        make.width.mas_equalTo(topInnerView.mas_height).multipliedBy(3);
        make.center.mas_equalTo(topView);
        
        // 设置优先级
        make.width.height.mas_equalTo(topView).priorityLow();
        make.width.height.lessThanOrEqualTo(topView);
    }];
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(topView);
        make.top.mas_equalTo(topView.mas_bottom);
    }];
    
    // width/height比为1/3.0，要求是同一个控件的属性比例
    [bottomInnerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(bottomView);
        make.center.mas_equalTo(bottomView);
        // 注意，这个multipliedBy的使用只能是设置同一个控件的，比如这里的bottomInnerView，
        // 设置高/宽为3:1
        make.height.mas_equalTo(bottomInnerView.mas_width).multipliedBy(3);
        
        make.width.height.mas_equalTo(bottomView).priorityLow();
        make.width.height.lessThanOrEqualTo(bottomView);
    }];
}

/**复合view循环动画**/
- (void)testx{
    UIView *lastView = self.view;
    for (int i = 0; i < 6; i++) {
        UIView *view = UIView.new;
        view.backgroundColor = [self randomColor];
        view.layer.borderColor = UIColor.blackColor.CGColor;
        view.layer.borderWidth = 2;
        [self.view addSubview:view];
        
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(lastView).insets(UIEdgeInsetsMake(20, 20, 20, 20));
        }];
        
        lastView = view;
        
        [self.viewArray addObject:view];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                              action:@selector(onTap1)];
        [view addGestureRecognizer:tap];
    }
    self.isNormal = YES;
}

- (void)onTap1 {
    UIView *lastView = self.view;
    
    if (self.isNormal) {
        for (NSInteger i = self.viewArray.count - 1; i >= 0; --i) {
            UIView *itemView = [self.viewArray objectAtIndex:i];
            [itemView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(lastView).insets(UIEdgeInsetsMake(20, 20, 20, 20));
            }];
            
            [self.view bringSubviewToFront:itemView];
            lastView = itemView;
        }
    } else {
        for (NSInteger i = 0; i < self.viewArray.count; ++i) {
            UIView *itemView = [self.viewArray objectAtIndex:i];
            [itemView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(lastView).insets(UIEdgeInsetsMake(20, 20, 20, 20));
            }];
            
            [self.view bringSubviewToFront:itemView];
            lastView = itemView;
        }
    }
    
    [self.view setNeedsUpdateConstraints];
    [self.view updateConstraintsIfNeeded];
    
    [UIView animateWithDuration:0.5 animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        self.isNormal = !self.isNormal;
    }];
}

- (NSMutableArray *)viewArray {
    if (_viewArray == nil) {
        _viewArray = [[NSMutableArray alloc] init];
    }
    return _viewArray;
}

//- (UIColor *)randomColor {
//    CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
//    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from white
//    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black
//    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
//}


/**子随父动的方法**/
- (void)sonViewWithFatherView{
    UIView *greenView = [[UIView alloc] init];
    greenView.backgroundColor = UIColor.greenColor;
    greenView.layer.borderColor = UIColor.blackColor.CGColor;
    greenView.layer.borderWidth = 2;
    [self.view addSubview:greenView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap)
                                   ];
    [greenView addGestureRecognizer:tap];
    self.greenView = greenView;
    
    
    
    
    UIView *blueView = UIView.new;
    blueView.backgroundColor = UIColor.blueColor;
    blueView.layer.borderColor = UIColor.blackColor.CGColor;
    blueView.layer.borderWidth = 2;
    [self.view addSubview:blueView];
    self.blueView = blueView;
    
    
    // 这里，我们不使用updateViewConstraints方法，但是我们一样可以做到。
    // 不过苹果推荐在updateViewConstraints方法中更新或者添加约束的
    [self updateWithExpand:NO animated:NO];
    
    
    
    UILabel *label = [[UILabel alloc] init];
    label.numberOfLines = 0;
    label.textColor = [UIColor redColor];
    label.font = [UIFont systemFontOfSize:16];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"点击绿色部分放大，蓝色部分最大值250，最小值90";
    [self.greenView addSubview:label];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
    }];
}

- (void)updateWithExpand:(BOOL)isExpanded animated:(BOOL)animated {
    self.isExpaned = isExpanded;
    
    [self.greenView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        if (isExpanded) {
            make.bottom.mas_equalTo(-20);
        } else {
            make.bottom.mas_equalTo(-300);
        }
    }];
    
    [self.blueView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.greenView);
        
        // 这里使用优先级处理
        // 设置宽高，这里用的连贯操作
        if (!isExpanded) {
            make.width.height.mas_equalTo(100 * 0.5).priorityLow();
        } else {
            make.width.height.mas_equalTo(100 * 3).priorityLow();
        }
        
        // 最大值为250
        make.width.height.lessThanOrEqualTo(@250);
        
        // 最小值为90
        make.width.height.greaterThanOrEqualTo(@90);
    }];
    
    if (animated) {
        [self.view setNeedsUpdateConstraints];
        [self.view updateConstraintsIfNeeded];
        
        [UIView animateWithDuration:0.5 animations:^{
            [self.view layoutIfNeeded];
        }];
    }
}

- (void)onTap {
    [self updateWithExpand:!self.isExpaned animated:YES];
}

/**remark用法**/
- (void)remarkConstraints{
    self.remarkButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.remarkButton setTitle:@"点我展开" forState:UIControlStateNormal];
    self.remarkButton.layer.borderColor = UIColor.greenColor.CGColor;
    self.remarkButton.layer.borderWidth = 3;
    self.remarkButton.backgroundColor = [UIColor lightGrayColor];
    [self.remarkButton addTarget:self action:@selector(onGrowButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.remarkButton];
    self.isExpanded = NO;
    
    [self.remarkButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-350);
    }];
    
}

/**update用法**/
- (void)updateConstraints{
    self.growingButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.growingButton setTitle:@"点我放大" forState:UIControlStateNormal];
    self.growingButton.layer.borderColor = UIColor.greenColor.CGColor;
    self.growingButton.layer.borderWidth = 3;
    
    [self.growingButton addTarget:self action:@selector(onGrowButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.growingButton];
    
    
    //记录增加的量
    self.scacle = 1.0;
    
    [self.growingButton mas_updateConstraints:^(MASConstraintMaker *make) {
        //让按钮始终居中
        make.center.mas_equalTo(self.view);
        
        // 初始宽、高为100，优先级最低，就可以保证宽高不能超过屏幕。
        make.width.height.mas_equalTo(100 * self.scacle).priorityLow();
        // 最大放大到整个view
        make.width.height.lessThanOrEqualTo(self.view);
    }];
}


- (void)updateViewConstraints {
    [self.growingButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.view);
        
        // 初始宽、高为100，优先级最低
        make.width.height.mas_equalTo(100 * self.scacle).priorityLow();
        // 最大放大到整个view
        make.width.height.lessThanOrEqualTo(self.view);
    }];
    
    
    // 这里使用update也是一样的。
    // remake会将之前的全部移除，然后重新添加
    WS(weakSelf);
    [self.remarkButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
        if (weakSelf.isExpanded) {
            make.bottom.mas_equalTo(0);
        } else {
            make.bottom.mas_equalTo(-350);
        }
    }];
    
    
    [super updateViewConstraints];
}

- (void)onGrowButtonTaped:(UIButton *)sender {
    self.scacle += 0.5;
    
    
    self.isExpanded = !self.isExpanded;
    if (!self.isExpanded) {
        [self.remarkButton setTitle:@"点我展开" forState:UIControlStateNormal];
    } else {
        [self.remarkButton setTitle:@"点我收起" forState:UIControlStateNormal];
    }
    
    
    
    // 告诉self.view约束需要更新，这个比较重要
    [self.view setNeedsUpdateConstraints];
    // 调用此方法告诉self.view检测是否需要更新约束，若需要则更新，下面添加动画效果才起作用
    [self.view updateConstraintsIfNeeded];
    
    [UIView animateWithDuration:0.3 animations:^{
        //我们要使约束立即生效，就必须调用layoutIfNeeded此方法
        [self.view layoutIfNeeded];
    }];
}


/**基础用法**/
- (void)basicTest{
    UIView *greenView = UIView.new;
    greenView.backgroundColor = UIColor.greenColor;
    greenView.layer.borderColor = UIColor.blackColor.CGColor;
    greenView.layer.borderWidth = 2;
    
    [greenView showPlaceHolder];
    
    [self.view addSubview:greenView];
    
    UIView *redView = UIView.new;
    redView.backgroundColor = UIColor.redColor;
    redView.layer.borderColor = UIColor.blackColor.CGColor;
    redView.layer.borderWidth = 2;
    
    [redView showPlaceHolder];
    
    [self.view addSubview:redView];
    
    
    UIView *blueView = UIView.new;
    blueView.backgroundColor = UIColor.blueColor;
    blueView.layer.borderColor = UIColor.blackColor.CGColor;
    blueView.layer.borderWidth = 2;
    
    [blueView showPlaceHolder];
    
    [self.view addSubview:blueView];
    
    // 使这三个控件等高
    CGFloat padding = 10;
    [greenView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(padding);
        make.left.mas_equalTo(padding);
        make.right.mas_equalTo(redView.mas_left).offset(-padding);
        make.bottom.mas_equalTo(blueView.mas_top).offset(-padding);
        // 三个控件等高
        make.height.mas_equalTo(@[redView, blueView]);
        // 红、绿这两个控件等高
        make.width.mas_equalTo(redView);
    }];
    
    [redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.height.bottom.mas_equalTo(greenView);
        make.right.mas_equalTo(-padding);
        make.left.mas_equalTo(greenView.mas_right).offset(padding);
    }];
    
    [blueView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(greenView);
        make.bottom.mas_equalTo(-padding);
        make.left.mas_equalTo(padding);
        make.right.mas_equalTo(-padding);
    }];
}

- (void)test4{
    
    WS(ws);
    
    UIView *sv = [UIView new];
    //    [sv showPlaceHolder];
    sv.backgroundColor = [UIColor blackColor];
    [self.view addSubview:sv];
    
    [sv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(ws.view);
        make.size.mas_equalTo(CGSizeMake(300, 300));
    }];
    
    UIView *sv11 = [UIView new];
    UIView *sv12 = [UIView new];
    UIView *sv13 = [UIView new];
    UIView *sv21 = [UIView new];
    UIView *sv31 = [UIView new];
    sv11.backgroundColor = [UIColor redColor];
    sv12.backgroundColor = [UIColor redColor];
    sv13.backgroundColor = [UIColor redColor];
    sv21.backgroundColor = [UIColor redColor];
    sv31.backgroundColor = [UIColor redColor];
    [sv addSubview:sv11];
    [sv addSubview:sv12];
    [sv addSubview:sv13];
    [sv addSubview:sv21];
    [sv addSubview:sv31];
    //给予不同的大小 测试效果
    [sv11 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(@[sv12,sv13]);
        make.centerX.equalTo(@[sv21,sv31]);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    [sv12 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(70, 20));
    }];
    [sv13 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 50));
    }];
    [sv21 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 20));
    }];
    [sv31 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(40, 60));
    }];
    [sv distributeSpacingHorizontallyWith:@[sv11,sv12,sv13]];
    [sv distributeSpacingVerticallyWith:@[sv11,sv21,sv31]];
    [sv showPlaceHolderWithAllSubviews];
    [sv hidePlaceHolder];
}

- (void)test3{
    WS(ws);
    
    UIView *sv = [UIView new];
    //    [sv showPlaceHolder];
    sv.backgroundColor = [UIColor blackColor];
    [self.view addSubview:sv];
    
    [sv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(ws.view);
        make.size.mas_equalTo(CGSizeMake(300, 300));
    }];
    
    
    UIScrollView *scrollView = [UIScrollView new];
    scrollView.backgroundColor = [UIColor whiteColor];
    [sv addSubview:scrollView];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(sv).with.insets(UIEdgeInsetsMake(5,5,5,5));
    }];
    UIView *container = [UIView new];
    [scrollView addSubview:container];
    [container mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(scrollView);
        make.width.equalTo(scrollView);
    }];
    
    
    int count = 10;
    UIView *lastView = nil;
    for ( int i = 1 ; i <= count ; ++i ){
        UIView *subv = [UIView new];
        [container addSubview:subv];
        subv.backgroundColor = [UIColor colorWithHue:( arc4random() % 256 / 256.0 )
                                          saturation:( arc4random() % 128 / 256.0 ) + 0.5
                                          brightness:( arc4random() % 128 / 256.0 ) + 0.5
                                               alpha:1];
        
        [subv mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.equalTo(container);
            make.height.mas_equalTo(@(20*i));
            if ( lastView ){
                make.top.mas_equalTo(lastView.mas_bottom);
            }else{
                make.top.mas_equalTo(container.mas_top);
            }
        }];
        
        lastView = subv;
    }
    
    //这里的关键就在于container这个view起到了一个中间层的作用 能够自动的计算uiscrollView的contentSize
    [container mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(lastView.mas_bottom);
    }];
}

- (void)test2{
    WS(ws);
    UIView *sv = [UIView new];
    //    [sv showPlaceHolder];
    sv.backgroundColor = [UIColor blackColor];
    [self.view addSubview:sv];
    
    [sv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(ws.view);
        make.size.mas_equalTo(CGSizeMake(300, 300));
    }];
    
    UIView *sv2 = [UIView new];
    [sv2 showPlaceHolder];
    sv2.backgroundColor = [UIColor orangeColor];
    [sv addSubview:sv2];
    
    UIView *sv3 = [UIView new];
    [sv3 showPlaceHolder];
    sv3.backgroundColor = [UIColor orangeColor];
    [sv addSubview:sv3];
    
    int padding1 = 10;
    [sv2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(sv.mas_centerY);
        make.left.equalTo(sv.mas_left).with.offset(padding1);
        make.right.equalTo(sv3.mas_left).with.offset(-padding1);
        make.height.mas_equalTo(@150);
        make.width.equalTo(sv3);
    }];
    
    
    [sv3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(sv.mas_centerY);
        make.left.equalTo(sv2.mas_right).with.offset(padding1);
        make.right.equalTo(sv.mas_right).with.offset(-padding1);
        make.height.mas_equalTo(@150);
        make.width.equalTo(sv2);
    }];
}


- (void)test1{
    WS(ws);
    UIView *sv = [UIView new];
//    [sv showPlaceHolder];
    sv.backgroundColor = [UIColor blackColor];
    [self.view addSubview:sv];
    
    [sv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(ws.view);
        make.size.mas_equalTo(CGSizeMake(300, 300));
    }];
    
    UIView *sv1 = [UIView new];
    [sv1 showPlaceHolder];
    sv1.backgroundColor = [UIColor redColor];
    [sv addSubview:sv1];
    
    [sv1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(sv).with.insets(UIEdgeInsetsMake(10, 10, 10, 10));
        /* 等价于
         make.top.equalTo(sv).with.offset(10);
         make.left.equalTo(sv).with.offset(10);
         make.bottom.equalTo(sv).with.offset(-10);
         make.right.equalTo(sv).with.offset(-10);
         */
        
        /* 也等价于
         make.top.left.bottom.and.right.equalTo(sv).with.insets(UIEdgeInsetsMake(10, 10, 10, 10));
         */
    }];
}


- (void)test{
    WS(ws);
    
    //从此以后基本可以抛弃CGRectMake了
    UIView *sv = [UIView new];
    [sv showPlaceHolder]; //来自三方库
    sv.backgroundColor = [UIColor blackColor];
    //在做autoLayout之前 一定要先将view添加到superview上 否则会报错
    [self.view addSubview:sv];
    //mas_makeConstraints就是Masonry的autolayout添加函数 将所需的约束添加到block中行了
    [sv mas_makeConstraints:^(MASConstraintMaker *make) {
        //将sv居中(很容易理解吧?)
        make.center.equalTo(ws.view);
        
        //将size设置成(300,300)
        make.size.mas_equalTo(CGSizeMake(300, 300));
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
